import bs4
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p><body><html>
"""
soup = bs4.BeautifulSoup(html_doc,"lxml") # 读取文本
# soup = bs4.BeautifulSoup(open('1.html', encoding='utf8'),'lxml') 从文件中获取
# print(soup) # 原样输出
# print(soup.prettify()) # prettify：意思是把soup对象按html结构格式化的打印出来
# print(soup.title) #标题标签
# print(soup.title.name) # 标题名
# print(soup.title.attr) # 标题名
# print(soup.find("a")) # 获取第一个
# ---------------------------------------------
# print(soup.find_all("a")) # 获取多个,可以指定class
# print(soup.find_all(class_="sister")) # 指定class
# print(soup.find_all(id="link3")) # 指定class
# ---------------------------------------------
# tag = soup.find(id="link3")
# print(tag)
# print(tag.attrs) # 获取标签属性集合
# print(tag.name) # 获取标签类型
# print(tag.get("href")) # 获取具体属性,tag["href"]亦可
# print(tag.string) # 获取标签数据
# print([i.string for i in soup.find_all("a")]) # 输出多个标签的内容
# ---------------------------------------------
# css选择器：https://www.runoob.com/cssref/css-selectors.html
"""根据选择器获取标签列表"""
print(soup.select("p")) # 按照标签获取
print(soup.select("#id")) # 按照id获取
print(soup.select(".class")) # 按照class获取
print(soup.select("p>a")) # 按照css获取
print(soup.select("p>a:nth-child(2)")) # 按照css获取
print(soup.select("p>a:last-child")) # 按照css获取
print(soup.select("p>a:first-child")) # 按照css获取

"""嵌套选择"""
# lists = soup.select("ul>li")
# for i in lists:
#     print(i.select("span")[0].string)


